﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Krile.Kernel;
using Twinkle.Tweak;
using Twinkle.Common;
using Krile.Kernel.WindowsEx;
using System.Text.RegularExpressions;

namespace Twinkle.Dialogs
{
    public partial class ChirpStream : Form
    {
        public ChirpStream()
        {
            InitializeComponent();
            SetEnabled(false);
        }

        private void unlocker_CheckedChanged(object sender, EventArgs e)
        {
            SetEnabled(unlocker.Checked);
        }

        private void SetEnabled(bool ena)
        {
            IDText.Enabled = ena;
            PassText.Enabled = ena;
            button1.Enabled = ena;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Tweak.Streaming.IsStreaming)
            {
                MessageBox.Show("Streaming have already started.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            Tweak.Streaming.OnReceivedStatus += new Action<Tweak.TStatus>(TreatRecv);
            Tweak.Streaming.OnDisconnected += new Action(Streaming_OnDisconnected);
            
            if (Tweak.Streaming.StartStreaming(new Tweak.CredentialProviders.Basic(IDText.Text, PassText.Text), Tweak.Streaming.StreamingType.chirp, Tweak.Streaming.DataObserveMode.CallbackEvents))
            {
                Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
                this.Close();
            }
            else
            {
                MessageBoxEx.Show("Start error!", "Unknown error", "Chirp error", MessageBoxEx.MessageBoxExButtons.Close, MessageBoxEx.MessageBoxExIcon.Error);
            }
        }

        void Streaming_OnDisconnected()
        {
            Tweak.Streaming.EndStreaming();
            MessageBoxEx.Show("Streaming is disconnected.", "Re-connecting is available.", "Streaming notification", MessageBoxEx.MessageBoxExButtons.Close, MessageBoxEx.MessageBoxExIcon.Information);
        }

        void Application_ApplicationExit(object sender, EventArgs e)
        {
            Tweak.Streaming.EndStreaming();
        }

        private static Regex RTExtractRegex = new Regex(@".*RT (@[a-zA-Z0-9]+)(?::| ) ?(.*)");
        void TreatRecv(TStatus s)
        {
            AutoReceiver.RegistStatuses(Data.Account.OuterInjectionSetFnFilterNRecv(new[] { s }));
        }
    }
}
